package com.qf.controller;

import com.qf.enums.InterfaceExceptionEnums;
import com.qf.exception.SmsException;
import com.qf.form.SmsInterfaceForm;
import com.qf.service.SmsInterfaceService;
import com.qf.util.Result;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/22 11:28
 */

@RestController
public class InterfaceController {

    @Value("${ip-header}")
    private String ipHeader;

    @Autowired
    private SmsInterfaceService smsInterfaceService;

    @PostMapping("/sms/interface")
    public Result smsInterface(SmsInterfaceForm smsInterfaceForm, HttpServletRequest request){

        //获取用户请求时携带的ip地址信息
        String ip = this.getReallyIpAddress(request);

        //将ip地址封装到form对象中
        smsInterfaceForm.setIp(ip);

        try {
            //调用service，对参数进行一系列的校验
            smsInterfaceService.checkParameters(smsInterfaceForm);
            //返回
            return Result.ok("接收成功");
        } catch (SmsException e) {
            if (e.getCode() == InterfaceExceptionEnums.INTERFACE_MOBILE_ERROR.getCode()&&e.getData()!=null){
                //返回带data的错误
                return Result.errorData(e);
            }else {
                //返回普通错误
                return Result.error(e);
            }
        }


    }

    private String getReallyIpAddress(HttpServletRequest request) {
        //校验使用@Value注入的请求头没问题
        if (!StringUtils.isEmpty(ipHeader)&&ipHeader.length()>0){
            //将字符串用，分割为字符串数组，并进行遍历
            for (String header : ipHeader.split(",")) {
                //通过request，从请求头中获取真实IP
                String ip = request.getHeader(header);
                //判断是否拿到了真实的地址
                if (!StringUtils.isEmpty(ip)&&"unknow".equalsIgnoreCase(ip)){
                    return ip;
                }
            }
        }
        //循环结束还是没有拿到ip地址，通过传统方式获取ip
        return request.getRemoteAddr();
    }
}
